<template>
  <div class="ruleSet-library">
    <div class="left" :span="5">
      <LeftTree :type="3" @item-change="treeItemChange" />
    </div>
    <div class="right" :span="19">
      <MainPage v-if="currentData.propertyName || isLoading" :title="currentData.propertyName">
        <div class="content">
          <div class="search">
            <el-input
              v-model="keyWord"
              style="width: 240px"
              placeholder="请输入变量名称"
              @keyup.native.enter="searchData"
            ></el-input>
            <el-button type="primary" @click="searchData">搜索</el-button>
            <el-button type="text" @click="clearClick">清空搜索</el-button>
            <el-button type="primary" style="margin-left: auto" @click="addRuleSetClick({ parameterId: 0 })">
              新建
            </el-button>
          </div>
          <div class="table-wrap">
            <FormTable
              ref="formTable"
              :table-label="tableLabel"
              row-key="parameterId"
              default-expand-all
              :table-data="tableData"
            >
              <template #operation="{ row }">
                <el-link
                  type="primary"
                  :disabled="!row.append"
                  :title="disabledTitle(row)"
                  :underline="false"
                  @click="addRuleSetClick(row)"
                >
                  {{ row.dataType === 3 ? '添加子元素' : '添加子对象' }}
                </el-link>
                <el-link type="primary" :underline="false" @click="editClcik(row)">编辑</el-link>
                <el-tooltip
                  v-if="row.referenced"
                  slot="reference"
                  class="item"
                  effect="dark"
                  content="信息已被使用，不可删除"
                  placement="right"
                >
                  <el-link type="primary" style="margin-left: 12px" :disabled="row.referenced" :underline="false">
                    删除
                  </el-link>
                </el-tooltip>
                <el-popconfirm
                  v-else
                  confirm-button-text="删除"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="将删除该变量下全部数据，是否确认删除?"
                  @confirm="delClick(row)"
                >
                  <el-link slot="reference" type="primary" style="margin-left: 12px" :underline="false">
                    删除
                  </el-link>
                </el-popconfirm>
              </template>
            </FormTable>
          </div>
        </div>
        <DetailForms ref="detailForms" :data-type-list="dataTypeList" @saved="getTableData" />
      </MainPage>
      <div v-else style="height: 100%; display: flex; justify-content: center; align-items: center">
        <el-empty :image-size="200"></el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Notification } from 'element-ui'
import DetailForms from './components/parameterDetailForms'
import { loadGridParameter, deleteParameter, loadDataTypeOptionList } from '@/api/rule-management'
import LeftTree from './components/LeftTree.vue'
import FormTable from '@/components/form-table/index.vue'
import defaultSettings from '@/settings'
import { generateUUID, findNode, postMessage, receivedMessage } from '@/utils/index'

import _ from 'lodash'
const keyWord = ref('')
const tableData = ref([])
let cloneTableData = []
const currentData = ref({})
const treeItemChange = (data) => {
  currentData.value = data ?? {}
  getTableData()
}
const clearClick = () => {
  keyWord.value = ''
  getTableData()
}
const isLoading = ref(true)
const disabledTitle = computed((row) => (row) => {
  if (row.append) {
    return ''
  } else {
    if (row.dataType === 3) {
      return '数组类型只能添加一个子元素'
    } else {
      return '数组和对象才能添加子元素/对象'
    }
  }
})
let loadGridParameterRequestId = generateUUID()
const getTableData = () => {
  isLoading.value = true
  if (defaultSettings.isWPF || defaultSettings.isCEF) {
    loadGridParameterRequestId = generateUUID()
    let message = {
      RequestUrl: process.env.VUE_APP_URL + '/parameter/loadGrid',
      RequestMethod: 'POST',
      Headers: {
        contentType: 'application/json'
      },
      QueryParameter: {},
      RequestBody: {
        parameterModuleId: currentData.value.id,
        searchName: keyWord.value
      },
      WebInfo: {
        requestId: loadGridParameterRequestId
      }
    }
    postMessage(message)
  } else {
    loadGridParameter({
      parameterModuleId: currentData.value.id,
      searchName: keyWord.value
    })
      .then(({ data }) => {
        cloneTableData = data
        tableData.value = _.cloneDeep(cloneTableData)
      })
      .finally(() => {
        isLoading.value = false
      })
  }
}

const filterMethods = (arr, keyword, first = true) => {
  if (first) {
    // 首次传入深度克隆数据防止修改源数据
    arr = JSON.parse(JSON.stringify(arr))
  }
  let emptyArr = []
  for (let item of arr) {
    if (item.parameterName.includes(keyword)) {
      if (item.children && Array.isArray(item.children) && item.children.length > 0) {
        item.children = filterMethods(item.children, keyword, false)
      }
      emptyArr.push(item)
    } else if (item.children && Array.isArray(item.children) && item.children.length > 0) {
      item.children = filterMethods(item.children, keyword, false)
      if (item.children.length) {
        emptyArr.push(item)
      }
    }
  }
  return emptyArr
}
const searchData = () => {
  if (keyWord.value) {
    tableData.value = filterMethods(cloneTableData, keyWord.value)
  } else {
    tableData.value = _.cloneDeep(cloneTableData)
  }
}
// 新增
const detailForms = ref()
const addRuleSetClick = (row) => {
  detailForms.value.show('add', currentData.value.id, row)
}
const editClcik = (data) => {
  let nameDisabled = false
  if (data.parentParameterId !== 0) {
    let parentNode = findNode(tableData.value, 'parameterId', data.parentParameterId, [])
    nameDisabled = parentNode.dataType === 3
  }
  detailForms.value.show('edit', data, { nameDisabled })
}

let deleteParameterRequestId = generateUUID()
const delClick = (data) => {
  const ids = []
  const getIds = (arr) => {
    arr.forEach((item) => {
      ids.push(item.parameterId)
      if (item.children?.length) {
        getIds(item.children)
      }
    })
  }
  getIds([data])
  if (defaultSettings.isWPF || defaultSettings.isCEF) {
    deleteParameterRequestId = generateUUID()
    let message = {
      RequestUrl: process.env.VUE_APP_URL + '/parameter/delete',
      RequestMethod: 'POST',
      Headers: {
        contentType: 'application/json'
      },
      QueryParameter: {},
      RequestBody: { ids },
      WebInfo: {
        requestId: deleteParameterRequestId
      }
    }
    postMessage(message)
  } else {
    deleteParameter({ ids }).then(() => {
      Notification({
        type: 'success',
        title: '成功',
        message: '删除完成'
      })
      getTableData()
    })
  }
}

const dataTypeList = ref([])
let loadDataTypeOptionListRequestId = generateUUID()
if (defaultSettings.isWPF || defaultSettings.isCEF) {
  loadDataTypeOptionListRequestId = generateUUID()
  let message = {
    RequestUrl: process.env.VUE_APP_URL + '/parameter/loadDataTypeOptionList',
    RequestMethod: 'POST',
    Headers: {
      contentType: 'application/json'
    },
    QueryParameter: {},
    RequestBody: {},
    WebInfo: {
      requestId: loadDataTypeOptionListRequestId
    }
  }
  postMessage(message)
} else {
  loadDataTypeOptionList().then(({ data }) => {
    dataTypeList.value = data
  })
}

const dataHandle = (result) => {
  let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
  if (e.data.webInfo.requestId === loadGridParameterRequestId) {
    cloneTableData = e.data.response.data
    tableData.value = _.cloneDeep(cloneTableData)
    isLoading.value = false
  } else if (e.data.webInfo.requestId === deleteParameterRequestId) {
    let res = e.data.response
    if (res.success) {
      Notification({
        type: 'success',
        title: '成功',
        message: '删除完成'
      })
      getTableData()
    } else {
      Notification({
        type: 'error',
        title: '错误',
        message: res.message
      })
    }
  } else if (e.data.webInfo.requestId === loadDataTypeOptionListRequestId) {
    dataTypeList.value = e.data.response.data
  }
}
receivedMessage(dataHandle)

// 表格配置
const tableLabel = computed(() => [
  {
    prop: 'parameterName',
    label: '名称',
    minWidth: 200
  },
  // {
  //   prop: 'parameterKey',
  //   label: '参数英文名称'
  // },
  {
    prop: 'dataType',
    label: '数据类型',
    type: 'selectValue',
    selectOptions: dataTypeList.value
  },
  // {
  //   prop: 'required',
  //   label: '是否必填',
  //   type: 'selectValue',
  //   selectOptions: [
  //     { label: '否', value: 0 },
  //     { label: '是', value: 1 }
  //   ]
  // },
  {
    prop: 'description',
    label: '说明'
  },
  {
    prop: 'operation',
    type: 'slot',
    width: 480,
    label: '操作'
  }
])
</script>
<script>
export default {
  name: 'VariablesLibrary'
}
</script>
<style lang="less" scoped>
.ruleSet-library {
  height: 100%;
  display: flex;
  .left {
    background: #eff2f6;
    border-right: 1px solid #b9c8dc;
    color: 333;
    height: 100%;
    min-width: 304px;
    width: 304px;
    flex-shrink: 0;
  }
  .right {
    height: 100%;
    flex: 1;
    min-width: 500px;
    background-color: #fff;
  }
}
</style>
